package digital.store.springmvc.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;





import org.springframework.stereotype.Repository;

import digital.store.springmvc.dao.UserDao;
import digital.store.tutorial.springmvc.model.User;

@Repository
public class UserDaoImpl implements UserDao {
    @PersistenceContext
    private EntityManager em;
    
    public void saveOrUpdate(User user) {
        if (user.getId() != null) {
            em.merge(user);
        } else {
            em.persist(user);
        }
    }
    
    public void delete(Long id) {
        User user= findById(id);
        em.remove(user);
    }
    
    @SuppressWarnings("unchecked")
    public List<User> findAll() {
        return em.createQuery("SELECT u FROM User u").getResultList();
    }
    
    public User findById(Long id) {
        return em.find(User.class, id);
    }
    
    public User findByName(String firstName){
    	return em.find(User.class, firstName);
    }
    
    public User checkUser(String username,String password){
    	 return em.createQuery("SELECT u FROM user u WHERE u.username = '" + username  + "' and u.password = '" + password + "'",User.class).getSingleResult();
    }
}

